package com.coin900.coin.server.fu.ctrl;

import com.coin900.coin.base.CoinConstants;
import com.coin900.coin.base.utils.JavaSmsApi;
import com.coin900.coin.base.utils.ValidatorUtil;
import com.coin900.coin.persist.fu.FuUserVO;
import com.coin900.coin.server.BaseController;
import com.coin900.coin.service.fu.IFuSmsService;
import com.coin900.coin.service.fu.IFuUserService;
import com.value.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 短信/邮件发送
 *
 * @author shui
 * @create 2018-02-07
 **/
@Controller
public class MessageAndEmailCtrl extends BaseController {

    /**
     * 验证码过期时间 15 min ，15 * 60 = 900
     */
    private static int EXPIRETIME = 900;
    /**
     * 验证码重新发送最小时间 2 min, 900 - 2 * 60 = 780
     */
    private static int CODE_RESEND = 780;

    /**
     * 发送绑定手机号短信验证码
     *
     * @param mobile
     * @param request
     * @return
     */
    @RequestMapping(value = "/bind-mobile-code", method = RequestMethod.GET)
    public void sendCode(@RequestParam String mobile,
                         HttpServletRequest request) {
        if (!ValidatorUtil.checkMobile(mobile)) {
            throw new BusinessException("请输入正确的手机号");
        }
        String key = CoinConstants.COIN_SMS_CODE_MOBILE_BIND + mobile;
        this.sendSMS(key, mobile);
    }

    /**
     * 发送提现确认验证码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/withdraw-code", method = RequestMethod.GET)
    public void sendWithdrawCode(HttpServletRequest request) {
        FuUserVO user = super.getUser();
        FuUserVO dbUser = this.userService.getUser(user.getId());
        String mobile = dbUser.getMobile();
        String key = CoinConstants.COIN_SMS_CODE_WITHDRAW + mobile;
        this.sendSMS(key, mobile);
    }


    /**
     * 发送提现确认验证码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/order-pay-code", method = RequestMethod.GET)
    public void sendOrderPayCode(HttpServletRequest request) {
        FuUserVO user = super.getUser();
        FuUserVO dbUser = this.userService.getUser(user.getId());
        String mobile = dbUser.getMobile();
        String key = CoinConstants.COIN_SMS_CODE_ORDER_PAY + mobile;
        this.smsService.sendSMS(key, mobile);
    }

    /************************* 校验验证码 START *************************/


    /**
     * 校验绑定手机验证码是否正确
     *
     * @param code
     * @param request
     * @return
     */
    @RequestMapping(value = "/bind-mobile", method = RequestMethod.GET)
    public void securityCenter(@RequestParam String code,
                               @RequestParam String mobile,
                               HttpServletRequest request) {

        FuUserVO user = super.getUser();
        String key = CoinConstants.COIN_SMS_CODE_MOBILE_BIND;
        if (this.verifyCode(code, key, mobile)) {
            user.setMobile(mobile);
            user.setMoblieStatus(1);
            this.userService.updateFuUser(user);
        } else {
            throw new BusinessException("验证码错误");
        }
    }

    /************************* 校验验证码 END *************************/

    /**
     * 发送短信，并存储到 redis
     *
     * @param key    redis 中存储的 key
     * @param mobile 手机号
     */
    private void sendSMS(String key, String mobile) {
        String code = this.generateCode();
        if (this.redisTemplate.getExpire(key) < CODE_RESEND) {
            try {
                /****** 配置短信模板 ******/
                String text = "您的验证码是" + code;
                JavaSmsApi.sendSms(text, mobile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            this.redisTemplate.opsForValue().set(key, code);
            this.redisTemplate.expire(key, EXPIRETIME, TimeUnit.SECONDS);
        } else {
            throw new BusinessException("验证码已经发送");
        }
    }

    /**
     * 校验验证码是否正确
     *
     * @param code   用户输入的验证码
     * @param key    redis 中对应的 key
     * @param mobile 用户手机号
     * @return
     */
    private boolean verifyCode(String code, String key, String mobile) {
        String redisCode = (String) this.redisTemplate.opsForValue().get(key + mobile);
        if (!code.equals(redisCode)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取 6 位随机验证码
     *
     * @return
     */
    private String generateCode() {
        String code = "";
        for (int i = 0; i < 6; i++) {
            code = code + String.valueOf((int) Math.floor(Math.random() * 9 + 1));
        }
        return code;
    }

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private IFuUserService userService;
    @Autowired
    private IFuSmsService smsService;
}